package com.hzxgs.tracelogstarter.trace;

import com.hzxgs.tracelogstarter.properties.TraceProperties;
import com.hzxgs.tracelogstarter.util.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@ConditionalOnClass(value = { HttpServletRequest.class, OncePerRequestFilter.class })
@Order(TraceUtils.FILTER_ORDER)
@Slf4j
public class WebTraceFilter extends OncePerRequestFilter {

    @Resource
    private TraceProperties traceProperties;

    @Override
    public boolean shouldNotFilter(HttpServletRequest request) {
        return !traceProperties.getEnable();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            long startTime = System.currentTimeMillis();
            String requestURI = request.getRequestURI();
            String traceId = request.getHeader(TraceUtils.TRACE_ID_HEADER);
            String spanId = request.getHeader(TraceUtils.SPAN_ID_HEADER);
            if (StringUtils.isBlank(traceId)) {
                TraceUtils.addTrace();
            } else {
                TraceUtils.putTrace(traceId, spanId);
            }
            filterChain.doFilter(request, response);
            int status = response.getStatus();
            log.info("{}, {}, {} ms", requestURI, status, System.currentTimeMillis() - startTime);
        } finally {
            TraceUtils.removeTrace();
        }
    }
}
